package com.iweb.user.service;

import com.iweb.user.dao.UserOrderMapper;
import com.iweb.user.dao.UserRefundMapper;
import com.iweb.user.dao.UserSeatMapper;
import com.iweb.user.dao.UserShowsMapper;
import com.iweb.user.dao.UserTicketMapper;
import com.iweb.user.model.Order;
import com.iweb.user.model.Refund;
import com.iweb.user.model.Seat;
import com.iweb.user.model.Show;
import com.iweb.user.model.Ticket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Date;

@Service
public class UserOrderServiceImpl implements UserOrderService {

    @Autowired
    private UserSeatMapper userSeatMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private UserRefundMapper userRefundMapper;
    @Autowired
    private UserShowsMapper userShowsMapper;
    @Autowired
    private UserTicketMapper userTicketMapper;

    @Override
    public Order createOrder(Order orderFromFrontend) {
        int updatedRows = userSeatMapper.updateStatusToSold(orderFromFrontend.getSeatId());

        if (updatedRows == 0) {
            return null;
        }

        int userId = orderFromFrontend.getUserId();
        int showId = orderFromFrontend.getShowId();
        int seatId = orderFromFrontend.getSeatId();

        Seat seat = userSeatMapper.selectById(seatId);
        if (seat == null) {
            throw new RuntimeException("购票失败：座位信息不存在，请联系管理员。");
        }

        Show show = userShowsMapper.selectShowById(showId);
        if (show == null) {
            throw new RuntimeException("购票失败：演出信息不存在。");
        }

        List<Ticket> tickets = userTicketMapper.queryByShowId(showId);
        if (tickets == null || tickets.isEmpty()) {
            throw new RuntimeException("购票失败：该演出的票务信息未配置。");
        }

        BigDecimal price = null;
        for (Ticket ticket : tickets) {
            if (ticket.getCategory().equals(seat.getCategory())) {
                price = BigDecimal.valueOf(ticket.getPrice());
                break;
            }
        }

        if (price == null) {
            throw new RuntimeException("购票失败：未找到座位对应的票价，请联系管理员。");
        }

        Order finalOrder = new Order();
        finalOrder.setUserId(userId);
        finalOrder.setShowId(showId);
        finalOrder.setSeatId(seatId);
        finalOrder.setShowName(show.getShowName());
        finalOrder.setCategory(seat.getCategory());
        finalOrder.setRowNum(seat.getRowNum());
        finalOrder.setColNum(seat.getColNum());
        finalOrder.setPrice(price);
        finalOrder.setCreateTime(new Date());
        finalOrder.setStatus("已付款"); // <-- 明确设置状态

        userOrderMapper.insert(finalOrder);

        return finalOrder;
    }

}
